// 购物车食品的控制器

const FoodModel = require('../models/foodModel')

// 查询 
exports.query = async(req, res) => {
    const { userId } = req.body
    req.body.userId = userId
    const data = await FoodModel.find({
        userId
    })
    res.send({
        code: 0,
        msg: 'ok',
        data
    })
}

// 加入购物车
exports.join = async(req, res) => {
    const { userId, foodId, foodNum} = req.body
    let data = await FoodModel.findOne({userId, foodId})
    if(!data) {
        await FoodModel.create(req.body)
    }else {
        let num = data.foodNum * 1 + foodNum * 1
        console.log(data.foodNum)
        console.log(foodNum)
        data = await FoodModel.updateOne({_id: data._id}, {foodNum: num})
    }
    res.send({
        code: 0,
        msg: 'ok'
    })
}

// 更新购物车
exports.update = async(req, res) => {
    const { userId, foodId, foodNum } = req.body
    const data1 = await FoodModel.findOne({userId, foodId})
    let num = foodNum * 1
    const data = await FoodModel.updateOne({_id: data1._id}, {foodNum: num})
    res.send({
        code: 0,
        msg: 'ok',
    })
}

// 删除
exports.remove = async( req, res ) => {
    const { userId, foodId } = req.body
    await FoodModel.deleteOne({userId, foodId})
    res.send({
        code: 0,
        msg: 'ok'
    })
}